package com.dabai.applicationmanager.ui;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.MenuItem;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.NotificationCompat;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

import com.dabai.applicationmanager.R;
import com.dabai.applicationmanager.dialog.MdcDialog;
import com.dabai.applicationmanager.utils.OtherUtils;
import com.dabai.dbutils.manager.CacheDataManager;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.AppUtils;
import com.dabai.dbutils.utils.DabaiUtils;
import com.dabai.dbutils.utils.FileUtils;
import com.dabai.dbutils.utils.SharedPreferencesBasicUse;
import com.dabai.dbutils.utils.StringUtils;
import com.dabai.uitools.base.BaseAppCompatActivity;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.io.File;
import java.util.Arrays;

public class SettingsActivity extends BaseAppCompatActivity {

    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.settings, new SettingsFragment())
                    .commit();
        }
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        context = this;

        SharedPreferencesBasicUse.init(context);

    }


    public static class SettingsFragment extends PreferenceFragmentCompat {

        private Context context;
        Handler handler = new Handler();


        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);
            context = getContext();


            final Preference preferenceItem = getPreferenceManager().findPreference("extractDir");
            assert preferenceItem != null;
            preferenceItem.setSummary(OtherUtils.getExportDirectory(context).getAbsolutePath());


        }

        @Override
        public boolean onPreferenceTreeClick(Preference preference) {

            switch (preference.getKey()) {
                case "sorting_way":
                    if (DabaiUtils.isFunctionFirstOpen(context, "sorting_way")) {
                        DBToast.showText(context, "刷新应用列表生效!");
                    }
                    break;
                case "applicationSupport":
                    DabaiUtils.openLinkWithBrowserActivity(context, "https://support.qq.com/embed/phone/345667/faqs-list/70591");
                    break;
                case "recommend1":
                    DabaiUtils.openLink(context, "https://www.coolapk.com/apk/com.dabai.opdoubleopen");
                    break;
                case "recommend2":
                    DabaiUtils.openLink(context, "https://www.coolapk.com/apk/com.dabai.markdownq");
                    break;
                case "applicationDetails":
                    DabaiUtils.toMyAppInfo(context);
                    break;
                case "uninstallProgram":
                    AppUtils.uninstallApk(context, context.getPackageName());
                    break;
                case "notificationBarSchedule":
                    boolean notificationBarSchedule = preference.getSharedPreferences().getBoolean("notificationBarSchedule", false);
                    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

                    if (notificationBarSchedule) {

                        Notification notification = new NotificationCompat.Builder(context, "extract_progress")
                                .setSmallIcon(R.drawable.ic_round_android_24)
                                .setContentTitle("测试通知")
                                .setContentText("进度通知已经成功开启!")
                                .build();

                        notification.flags |= Notification.FLAG_AUTO_CANCEL;

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

                            //通知 强度
                            int importance = NotificationManager.IMPORTANCE_HIGH;
                            NotificationChannel channel = new NotificationChannel("extract_progress", "执行进度", importance);
                            notificationManager.createNotificationChannel(channel);

                        }
                        notificationManager.notify(100, notification);

                    } else {
                        notificationManager.cancel(100);
                    }
                    break;
                case "openShizuku":

                    if (AppUtils.isAppInstalled(context, "moe.shizuku.privileged.api")) {
                        AppUtils.openApp(context, "moe.shizuku.privileged.api");
                        DBToast.showYellowToast(context, "请授权本应用:应用程序管理(" + context.getPackageName() + ")");
                    } else {
                        DBToast.showYellowToast(context, "请先安装shizuku管理器");
                        DabaiUtils.openLink(context, "https://dabai2017.gitee.io/blog/2021/07/24/shizuku%E4%BD%BF%E7%94%A8%E5%B8%AE%E5%8A%A9/");
                    }
                    break;
                case "extractNamingRules":

                    MdcDialog.showInputDialog(context, "命名规则"
                            , SharedPreferencesBasicUse.getString("extractNamingRules", "&n_&vn_&vc")
                            , "提取命名规则"
                            , new MdcDialog.OnInputDialogButtonListener() {
                                @Override
                                public void confirm(AlertDialog dialog, String content) {
                                    if (!content.contains("&n")) {
                                        DBToast.showText(context, "至少包含一个\"&n\"函数", false);
                                        return;
                                    }
                                    String[] sp = new String[]{
                                            "/", "\\", "|", ">", "<", "?", "*", ":", " ", "\n"};
                                    if (StringUtils.contains(content, sp)) {
                                        DBToast.showText(context, "不能包含特殊符号 " + Arrays.toString(sp).replaceAll("\n", "换行"), false);
                                        return;
                                    }
                                    SharedPreferencesBasicUse.setString("extractNamingRules", content);
                                    dialog.dismiss();
                                    DBToast.showText(context, "修改完成!", true);

                                }

                                @Override
                                public void cancel() {

                                }
                            }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

                    break;
                case "extractDir":

                    String inDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "AppExtract").getAbsolutePath();
                    String outDir = context.getExternalFilesDir("AppExtract").getAbsolutePath();

                    String dir = SharedPreferencesBasicUse.getString("extractDir", inDir);

                    new MaterialAlertDialogBuilder(context, R.style.DBTheme_Dialog_RoundTheme)
                            .setTitle("提取到")
                            .setSingleChoiceItems(new String[]{"下载文件夹", "应用私有文件夹"}, inDir.equals(dir) ? 0 : 1, (dialog, which) -> {

                                if (which == 0) {
                                    SharedPreferencesBasicUse.setString("extractDir", inDir);
                                } else {
                                    SharedPreferencesBasicUse.setString("extractDir", outDir);
                                }

                                final Preference preferenceItem = getPreferenceManager().findPreference("extractDir");
                                assert preferenceItem != null;
                                preferenceItem.setSummary(OtherUtils.getExportDirectory(context).getAbsolutePath());

                                dialog.dismiss();

                            }).show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

                    break;
                case "clearExtractFile":

                    MdcDialog.showConfirmDialog(context, "提示"
                            , "是否删除所有提取的文件,删除后大约释放 "
                                    + FileUtils.formatFileSizeToString(
                                    FileUtils.getFileSize(context.getExternalCacheDir())
                                            + FileUtils.getFileSize(OtherUtils.getExportDirectory(context))) +
                                    " 的容量", new MdcDialog.OnConfirmDialogButtonListener() {
                                @Override
                                public void confirm() {
                                    new Thread(() -> {
                                        CacheDataManager.clearAllCache(context);
                                        boolean isOk = FileUtils.delete(OtherUtils.getExportDirectory(context));
                                        handler.post(() -> DBToast.showMethodsFeedbackText(context
                                                , isOk
                                                , "删除成功!", "删除失败!"));
                                    }).start();
                                }

                                @Override
                                public void cancel() {
                                }
                            }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

                    break;
                case "clearReceiveFile":

                    MdcDialog.showConfirmDialog(context, "提示"
                            , "是否删除所有互传接收的文件,删除后大约释放 "
                                    + FileUtils.formatFileSizeToString(
                                    FileUtils.getFileSize(context.getExternalCacheDir())
                                            + FileUtils.getFileSize(OtherUtils.getReceiveFileDirectory(context))) +
                                    " 的容量", new MdcDialog.OnConfirmDialogButtonListener() {
                                @Override
                                public void confirm() {
                                    new Thread(() -> {
                                        CacheDataManager.clearAllCache(context);
                                        boolean isOk = FileUtils.delete(OtherUtils.getReceiveFileDirectory(context));
                                        handler.post(() -> DBToast.showMethodsFeedbackText(context
                                                , isOk
                                                , "删除成功!", "删除失败!"));
                                    }).start();
                                }

                                @Override
                                public void cancel() {
                                }
                            }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

                    break;


            }
            return super.onPreferenceTreeClick(preference);
        }


    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


}